<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from '../plugins/axios' // 引入 axios 实例
import { ElPagination } from 'element-plus' // 引入 Element Plus 的分页组件
//import AnnouncementList from '../components/AnnouncementList.vue'
import AnnouncementSearch from '../components/AnnouncementSearch.vue'
import AnnouncementEditor from '../components/AnnouncementEditor.vue'  // 添加这行
import AnnouncementItem from '../components/AnnouncementItem.vue'

const router = useRouter()
const route = useRoute() // 使用 useRoute 获取路由信息

const announcements = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const pageSizes = [5, 10, 50, 100] // 每页显示个数选择器的选项设置
const canEdit = ref(false) // 根据用户权限判断
const isLoading = ref(false) // 加载状态

// 初始化搜索参数
const searchParams = ref({
  keyword: '', // 关键字
  siteId: 1, // 站点id，初始为 1（全站）
  userId: null, // user_id，可以根据需要传递
  startTime: '', // 开始时间
  endTime: '', // 结束时间
  top: route.params.id || 0, // 是否置顶，1 置顶，0 不置顶
  page: 1, // 页码
  rows: 5, // 每页条数
  sortWay: 'DESC', // 排序方式
  sortColumn: 'publish_time', // 排序字段，根据 publishTime 排序
  loginUserId: localStorage.getItem('userId'), // 当前登录的用户id，传递用户的id
})

// 获取公告列表数据
const fetchPublicData = async () => {
  try {
    // 修改为正确的API路径
    const response = await axios.post('/public/queryByCondition', searchParams.value)
    
    if (response.data.code === 1) {
      announcements.value = response.data.data
      totalCount.value = response.data.total
      console.log('获取数据成功:', announcements.value)
    } else {
      console.error('获取公告列表失败:', response.data.msg)
    }
  } catch (error) {
    console.error('获取公告列表请求失败:', error)
  }
}

// 搜索方法
const handleSearch = async (params) => {
  // 合并路由参数和搜索参数
  searchParams.value = {
    ...searchParams.value, // 保留原有参数
    ...params, // 合并传入的新参数
    page: currentPage.value,
    rows: pageSize.value
  }

  // 调用接口获取数据
  await fetchPublicData()
}

// 查看详情
const handleViewDetail = (announcement) => {
  router.push(`/announcement/${announcement.id}`)
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch(searchParams.value)
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch(searchParams.value)
}

// 在组件挂载时调用 handleSearch，传递默认参数
onMounted(() => {
  handleSearch({
    keyword: '',
    siteId: 1,
    userId: null,
    startTime: '',
    endTime: '',
    top: route.params.id || 0,
    page: currentPage.value,
    rows: pageSize.value,
    sortWay: 'DESC',
    sortColumn: 'publish_time',
    loginUserId: localStorage.getItem('userId')
  })
})

// 添加编辑器控制变量
const showEditor = ref(false)

// 添加编辑相关的响应式变量
const editData = ref(null)
const isEdit = ref(false)

// 修改编辑公告方法
const handleEdit = (announcement) => {
  showEditor.value = true
  editData.value = { ...announcement }
  isEdit.value = true
}

// 修改编辑器提交回调
const handleEditorSubmit = () => {
  fetchPublicData()
  // 重置编辑状态
  editData.value = null
  isEdit.value = false
}

// 添加站点选项
const siteOptions = ref([])

// 获取站点列表
const fetchSiteOptions = async () => {
  try {
    const userId = localStorage.getItem('userId')
    const response = await axios.get(`/site/findSiteByUserId/${userId}`)
    if (response.data.code === 1) {
      siteOptions.value = response.data.data
    } else {
      console.error('获取站点列表失败:', response.data.msg)
    }
  } catch (error) {
    console.error('获取站点列表请求失败:', error)
  }
}

// 修改 onMounted，添加获取站点列表的调用
onMounted(() => {
  fetchSiteOptions() // 添加这行
  handleSearch({
    keyword: '',
    siteId: 1,
    userId: null,
    startTime: '',
    endTime: '',
    top: route.params.id || 0,
    page: currentPage.value,
    rows: pageSize.value,
    sortWay: 'DESC',
    sortColumn: 'publish_time',
    loginUserId: localStorage.getItem('userId')
  })
})

// 处理删除
const handleDelete = async (announcement) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条公告吗？此操作不可恢复',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await axios.delete(`/announcement/delete/${announcement.id}`)
    
    if (response.data.code === 1) {
      ElMessage.success('删除成功')
      // 删除成功后重新获取数据
      await fetchPublicData()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

onMounted(() => {
  fetchPublicData()
})

</script>

<template>
  <div class="announcement-list-page">
    <div class="page-header">
      <h2>公告列表</h2>
      <el-button type="primary" @click="showEditor = true">发布公告</el-button>
    </div>

    <div class="search-section">
      <AnnouncementSearch @search="handleSearch" />
    </div>
    
    <div class="list-section">
      <!-- 加载中状态 -->
      <div v-if="isLoading" class="state-message">
        加载中...
      </div>
      
      <!-- 无数据状态 -->
      <div v-else-if="!announcements.length" class="state-message">
        暂无公告数据
      </div>
      
      <!-- 数据列表 -->
      <AnnouncementItem
        v-else
        :announcements="announcements"
        :canEdit="canEdit"
        @viewDetail="handleViewDetail"
        @edit="handleEdit"
        @delete="fetchPublicData"
        @refresh="fetchPublicData"
      />
    </div>

    <!-- Element Plus 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加公告编辑器组件 -->
    <AnnouncementEditor
      v-model:visible="showEditor"
      :site-options="siteOptions"
      :is-edit="isEdit"
      :edit-data="editData"
      @onSubmit="handleEditorSubmit"
    />
  </div>
</template>


<style scoped>
.announcement-list-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.search-section {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.list-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>